package edu.hwadee.BEIS.util;

import java.io.*;
import java.net.URLDecoder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import edu.hwadee.BEIS.constants.CustomException;
import edu.hwadee.BEIS.constants.ResultEnum;

/**
 * 文件管理工具类： 配置所有文件上传下载路径，提供各种文件操作
 *
 * @author kingsong
 */
@Component
public class FileUtil {

    private static String ProjectManage_FilePath;
    private static String AnnouncementAttachment_FilePath;
    /*private static String SchoolConditionAttachment_FilePath;*/
    private static String MajorCourseConstruction_FilePath;
/*    private static String GlobalCooperation_FilePath;
    private static String SchoolCompanyCooperation_FilePath;
    private static String VocationEducationalGroup_FilePath;*/


    public static String getMGGC_FilePath() {
        return MGGC_FilePath;
    }

    @Value("${user.file-path.mgcc-file}")
    public void setMGGC_FilePath(String MGGC_FilePath) {
        FileUtil.MGGC_FilePath = MGGC_FilePath;
    }

    private static String MGGC_FilePath;

    public static String getProjectManage_FilePath() {
        return ProjectManage_FilePath;
    }

    @Value("${user.file-path.project-management}")
    public void setProjectManage_FilePath(String projectManage_FilePath) {
        ProjectManage_FilePath = projectManage_FilePath;
    }

    public static String getAnnouncementAttachment_FilePath() {
        return AnnouncementAttachment_FilePath;
    }

    @Value("${user.file-path.announcement-attachment}")
    public void setAnnouncementAttachment_FilePath(String announcementAttachment_FilePath) {
        AnnouncementAttachment_FilePath = announcementAttachment_FilePath;
    }

    private static String ProjectDeclare;
    @Value("${user.file-path.project-declare}")
    public void setProjectDeclare_FilePath(String projectDeclare_filePath){
        ProjectDeclare = projectDeclare_filePath;
    }

    public static String getProjectDeclare_FilePath() {
        return ProjectDeclare;
    }







    /**
     * 保存上传文件
     *
     * @param type          所属情况类型
     * @param multipartFile 上传文件
     * @param fileName      保存名称
     * @return 返回本地文件绝对路径
     */
    public static String saveFile(String type, MultipartFile multipartFile, String fileName) {

        String path = "";
        switch (type) {
            case "analysisDiagram":
                path = getProjectManage_FilePath();
                break;
            case "announcement":
                path = getAnnouncementAttachment_FilePath();
                break;
            case "projectDeclare":
                path = getProjectDeclare_FilePath();
                break;
/*            case "schoolCondition":
                path = getSchoolConditionAttachment_FilePath();
                break;
            case "majorCourseConstruction":
                path = getMajorCourseConstruction_FilePath();
                break;
            case "globalCooperation":
                path = getGlobalCooperation_FilePath();
                break;
            case "schoolCompanyCooperation":
                path = getSchoolCompanyCooperation_FilePath();
                break;
            case "vocationEducationalGroup":
                path = getVocationEducationalGroup_FilePath();
                break;*/
            case "mgcc":
                path = getMGGC_FilePath();
                break;
            default:
                return "";
        }
        // 本地保存路径
        File file = new File(path + fileName);
//
        if (!file.getParentFile().exists()) {System.out.println(file.isAbsolute());
            // 父目录不存在，创建
            System.out.println(file.getParentFile().mkdirs());
        }
        try {
            // 保存上传文件到本地
            multipartFile.transferTo(file);
            return file.getAbsolutePath();
        } catch (Exception e) {
//            throw new CustomException(ResultEnum.FILE_SAVE_FAILURE);
            e.printStackTrace();
            return file.getAbsolutePath();
        }
    }

    /**
     * 删除本地文件：如分析图表
     *
     * @param filePath
     * @return
     */
    public static boolean deleteFile(String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            return false;
        } else {
            if (file.isFile()) {
                return file.delete();
            } else {
                return false;
            }
        }
    }

    /**
     * 解析XML文件
     *
     * @param filePath 文件本地路径
     * @return List<String> String类型集合
     */
    public static List<String> parseXML(String filePath) {
        List<String> res = null;
        try {
            if (new File(filePath).exists()) {
                res = new ArrayList<String>();
                // 获得文件输入流
                InputStream is = new FileInputStream(filePath);
                // 创建XML对象
                XSSFWorkbook xssfWorkbook = new XSSFWorkbook(is);
                // 获取第1个sheet
                XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(0);
                // 获取第二列
                for (int i = 0; i < xssfSheet.getLastRowNum(); i++) {
                    if (xssfSheet.getRow(i) != null) {
                        res.add(getValue(xssfSheet.getRow(i).getCell(1)));
                    } else {
                        continue;
                    }
                }
                return res;
            } else {
                return res;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return res;
        }
    }

    private static String getValue(XSSFCell xssfRow) {
        if (xssfRow != null) {
//            if (xssfRow != null) {
//                xssfRow.setCellType(xssfRow.CELL_TYPE_STRING);
//            }
            if (xssfRow.getCellType() == xssfRow.CELL_TYPE_BOOLEAN) {
                return String.valueOf(xssfRow.getBooleanCellValue());
            } else if (xssfRow.getCellType() == xssfRow.CELL_TYPE_NUMERIC) {
                String result = "";
                if (xssfRow.getCellStyle().getDataFormat() == 22) {
                    // 处理自定义日期格式：m月d日(通过判断单元格的格式id解决，id的值是58)
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    double value = xssfRow.getNumericCellValue();
                    Date date = org.apache.poi.ss.usermodel.DateUtil.getJavaDate(value);
                    result = sdf.format(date);
                } else {
                    double value = xssfRow.getNumericCellValue();
                    CellStyle style = xssfRow.getCellStyle();
                    DecimalFormat format = new DecimalFormat();
                    String temp = style.getDataFormatString();
                    // 单元格设置成常规
                    if (temp.equals("General")) {
                        format.applyPattern("#");
                    }
                    result = format.format(value);
                }
                return result;
            } else {
                return String.valueOf(xssfRow.getStringCellValue());
            }
        } else
            return null;
    }

    public static void main(String[] args) {
        System.out.println(parseXML("E:\\DownLoads\\专业年级课程建设.xlsx"));
    }
}
